package com.yunxi.exceptions;


import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.GlobalException;
import com.yunxi.core.web.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理
 */
@ControllerAdvice
public class ExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);

    /**
     * 异常处理
     *
     * @param e 异常信息
     */
    @org.springframework.web.bind.annotation.ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ApiResult handle(Exception e) {
        e = (Exception) get(e);
        if (e instanceof GlobalException) {
            GlobalException ex = (GlobalException) e;
            return ResponseUtil.fail(ex.getCode(), ex.getMessage());
        } else {
            logger.error("[系统异常]{}", e.getMessage(), e);
            return ResponseUtil.fail(502, e.getMessage());
//            return ResponseUtil.fail(500, "系统异常，请联系管理员");
        }
    }

    private Throwable get(Throwable e) {
        if (e.getCause() != null) {
            e = get(e.getCause());
        }
        return e;
    }
}
